/**
 * 渠道发布，发布记录（明细）
 */
import React from 'react';
import { Table, Form, Input, DatePicker, Button, message } from 'antd';
import { router, withRouter } from 'umi';
import moment from 'moment';
import { toNumber, isArray } from 'lodash';
import { Pagination, TableTreeFilter } from '@/components';
import { useRequest } from '@/hooks';
import { fetchCompany } from '@/containers/service';
import { Icon } from '../../../components';
import { getChannelPublishRecords } from '../../service';
import { getChannelListWithoutTalent } from '../../../Setting/service';
import styles from './index.less';

const TYPE = {
    1: '内部渠道',
    2: '外部渠道-招聘网站',
    3: '外部渠道-猎头公司'
};

const channelTypeList = [
    {
        value: '1',
        text: '内部渠道'
    },
    {
        value: '0',
        text: '外部渠道',
        children: [
            {
                value: '2',
                text: '招聘网站'
            },
            {
                value: '3',
                text: '猎头公司'
            }
        ]
    }
];

const operateTypeList = [
    {
        value: '1',
        text: '发布'
    },
    {
        value: '2',
        text: '更新'
    },
    {
        value: '3',
        text: '上线'
    },
    {
        value: '4',
        text: '下线'
    }
];

function HistoryPublish({ form, location }) {
    const { query = {} } = location;
    const { data, loading, run } = useRequest(getChannelPublishRecords, {
        manual: true
    });

    const dataSource = data?.data?.rows || [];
    const total = data?.data?.total || 0;
    const { data: orgList } = useRequest(
        () =>
            fetchCompany({
                organizationPermissions: 0
            }),
        {
            formatResult: res =>
                res?.data?.map(item => ({ value: item?.organizationCode, text: item?.organizationName }))
        }
    );

    const { data: channelList } = useRequest(() => getChannelListWithoutTalent({ channelStatus: 1 }), {
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data: temp, msg } = res;
                if (code === 10000) {
                    return temp.map(item => ({
                        text: item.channelName,
                        value: item.channelCode
                    }));
                }
                message.error(msg);
            }
            return [];
        }
    });
    // 兼容之前的逻辑
    const companyCodes = (channelCompanyCode = []) =>
        isArray(channelCompanyCode) ? channelCompanyCode : [channelCompanyCode];
    React.useEffect(() => {
        const {
            orderByField = '',
            channelType = [],
            operateType = [],
            channelCode = [],
            channelCompanyCode,
            activeKey,
            ...rest
        } = query;
        const channelTypes = isArray(channelType) ? channelType : [channelType];
        const operateTypes = isArray(operateType) ? operateType : [operateType];
        const channelCompanyCodes = companyCodes(channelCompanyCode);
        const channelCodes = isArray(channelCode) ? channelCode : [channelCode];
        run({
            ...rest,
            orderByField: orderByField.replace('end', ''),
            channelTypes: channelTypes.map(item => toNumber(item)),
            operateTypes: operateTypes.map(item => toNumber(item)),
            channelCompanyCodes,
            channelCodes
        });
    }, [query]);

    const columns = [
        {
            title: '渠道',
            dataIndex: 'channelName',
            filteredValue:
                query?.channelCode && (isArray(query?.channelCode) ? query?.channelCode : [query?.channelCode]),
            filters: channelList
        },
        {
            title: '类型',
            dataIndex: 'channelType',
            filteredValue:
                query?.channelType && (isArray(query?.channelType) ? query?.channelType : [query?.channelType]),
            filters: channelTypeList,
            filterDropdown: filterProps => <TableTreeFilter {...filterProps} />,
            render: text => TYPE[text] || ''
        },
        {
            title: '行政机构',
            dataIndex: 'channelCompanyCode',
            filteredValue: companyCodes(query.channelCompanyCode),
            filters: orgList,
            render: (_, row) => row?.companyName
        },
        {
            title: '岗位',
            dataIndex: 'dutyName'
        },
        {
            title: '操作',
            dataIndex: 'operateType',
            filteredValue:
                query?.operateType && (isArray(query?.operateType) ? query?.operateType : [query?.operateType]),
            filters: operateTypeList,
            render: text => operateTypeList.find(item => item.value === `${text}`)?.text || text
        },
        {
            title: '操作人',
            dataIndex: 'operateUserName'
        },
        {
            title: '账号',
            dataIndex: 'operateAccount',
            render: text => text || '--'
        },
        {
            title: '时间',
            dataIndex: 'operateTime',
            sortOrder: query.orderByField ? query.orderByField.split('|')[1] : undefined,
            sorter: () => {},
            render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : text)
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            className: styles.centerTable,
            render: record => (
                <Icon
                    type="yuanshijianli"
                    title="查看发布信息"
                    onClick={() => {
                        const q = {
                            id: record.id
                        };
                        if (record?.channelType === 3) {
                            q.channelType = 3;
                        } else {
                            q.recruitCode = record.recruitCode;
                        }
                        history.push({
                            pathname: '/office/personnelManagement/recruitment/channel/history/detail',
                            query: {
                                ...q
                            }
                        });
                    }}
                />
            )
        }
    ];

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        history.push({ query: { ...query, pageNo: current, pageSize } });
    };

    const handleTableChange = (_, filters = {}, sorter) => {
        const { channelType, operateType, channelName, channelCompanyCode } = filters;
        const { field, order } = sorter;
        history.push({
            query: {
                ...query,
                channelCode: channelName,
                channelType,
                operateType,
                channelCompanyCode,
                orderByField: order ? `${field}|${order}` : '',
                pageNo: 1
            }
        });
    };

    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (!err) {
                const { rangeTime, ...rest } = values;
                history.push({
                    query: {
                        ...query,
                        ...rest,
                        operateStartDate: rangeTime?.length > 0 ? rangeTime[0].format('YYYY-MM-DD') : '',
                        operateEndDate: rangeTime?.length > 1 ? rangeTime[1].format('YYYY-MM-DD') : '',
                        pageNo: 1
                    }
                });
            }
        });
    };

    return (
        <>
            <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 16 }}>
                {!query?.recruitCode && (
                    <Form.Item label="岗位">
                        {form.getFieldDecorator('dutyName', {
                            initialValue: query?.dutyName || ''
                        })(<Input style={{ width: 148 }} placeholder="请输入岗位" allowClear />)}
                    </Form.Item>
                )}
                <Form.Item label="操作人">
                    {form.getFieldDecorator('operateUserName', {
                        initialValue: query?.operateUserName || ''
                    })(<Input style={{ width: 148 }} placeholder="请输入操作人" allowClear />)}
                </Form.Item>
                <Form.Item label="账号">
                    {form.getFieldDecorator('operateAccount', {
                        initialValue: query?.operateAccount || ''
                    })(<Input style={{ width: 148 }} placeholder="请输入账号" allowClear />)}
                </Form.Item>
                <Form.Item label="时间">
                    {form.getFieldDecorator('rangeTime', {
                        initialValue:
                            query?.operateStartDate && query?.operateEndDate
                                ? [moment(query.operateStartDate), moment(query.operateEndDate)]
                                : undefined
                    })(<DatePicker.RangePicker style={{ width: 220 }} />)}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>
            </Form>
            <Table
                rowKey="id"
                columns={columns}
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onChange={handleTableChange}
                loading={loading}
            />
            <Pagination
                current={query.pageNo}
                pageSize={query.pageSize}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />
        </>
    );
}

export default withRouter(Form.create()(HistoryPublish));
